<?php
namespace app\admin\controller;

use think\Controller;
use think\Db;
use think\Model;
use \think\Session;
use think\Request;

class Product extends CommonController
{
	public function addProduct()
	{
		if (request()->isPost()) 
		{
			// 获取当前userid
			$userid = Session::get('userId');

			$adminUserName = Session::get('account');

			$productModel = model('product');

			$data = input('post.');

			// 设置年利率
			if ($data['deadLine'] == 2) {
				$data['interestRate'] = '0.06';
			} else if ($data['deadLine'] == 5) {
				$data['interestRate'] = '0.1';
			} else {
				$data['interestRate'] = '0.12';
			}

			$data['startTime'] = strtotime($data['startTime']);

			$data['endTime'] = strtotime($data['endTime']);

			$data['addUserId'] = $userid;

			$data['adminUserName'] = $adminUserName;

			$data['surplusMoney'] = $data['totalSum'];

			$data['updateTime'] = time();

			$productRes = $productModel->insert($data);

			if ($productRes)
			{
				return $this->redirect('product/listProduct');
			}
		}
		else
		{
			return $this->fetch('addProduct');
		}
	}

	/**
 	 * 产品列表
	 */
	public function listProduct()
	{
		if (request()->isPost()) 
		{
			$p = input('post.p');

			$start = ($p-1)*5;

			$productList = Db('product')->limit($start,5)->select();

			$productList = $this->productList($productList);

			echo json_encode(array('error'=>0,'data'=>$productList,'p'=>$p));
		}
		else
		{
			$productModel = model('product');

			$productList = $productModel->select();

			//获取总条数
			$productCount = Db::table('product')->count();

			$productCount = ceil($productCount/5);

			$productList = $this->productList($productList);

			return $this->fetch('listProduct',['productList'=>$productList,'last'=>$productCount]);
		}
	}
	/**
	 * 处理产品列表数据
	*/
	public function productList($productList)
	{
		foreach ($productList as $k => $v) 
		{
			$productList[$k]['startTime'] = date('Y-m-d', $v['startTime']);

			$productList[$k]['endTime'] = date('Y-m-d', $v['endTime']);

			if($v['status'] == 0){
				$productList[$k]['status'] = '未审核';
			} else if ($v['status'] == 1) {
				$productList[$k]['status'] = '已通过';
			} else {
				$productList[$k]['status'] = '未通过';
			}
		}
		return $productList;
	}

	/**
	 * 审核产品
	*/
	public function auditProduct()
	{
		if (request()->isPost()) 
		{
			$productId = input('post.productId');

			$status = input('post.status');

			if($status == 1)
			{
				$res = Db::table('product')->update(['status'=>1,'productId'=>$productId]);
			}
			else if($status == 2)
			{
				$res = Db::table('product')->update(['status'=>2,'productId'=>$productId]);
			}
			
			return json_encode($res);	
		}
		else
		{
			$productList = Db::table('product')->where('status',0)->select();

			$UnauditedProduct = $this->productList($productList);

			return $this->fetch('auditProduct',['UnauditedProduct'=>$UnauditedProduct]);
		}
	}
}